<template>
    <ayjDrawer class="sales-box " :title="'开机记录'" width="40%" ref="ayjDrawerRef" :slotFooter="false"
        @closeFun="handleClose">
        <div ref="containerBoxRef" class="container_box">
            <div ref="pointsBoxRef">
                <div class="flex_row mt5 mb10" v-if="isShowDevno">
                    <div class="costom-info">
                        <span class="font_black8">设备编号：</span>
                        <span class="bold font_yellow">{{ rowData.devno || "暂无编号" }}</span>
                    </div>
                    <div class="ml20 ">
                        <span class="font_black8">设备型号：</span>
                        <span class="bold">{{ rowData.type_name || "暂无型号" }}</span>
                    </div>
                </div>
                <div class="dialog-content-header flex_row mb5" v-if="!isShowDevno">
                    <Select v-model="query.shopid" :options="yunShopList" :placeholder="'选择云店'" :size="'mini'"
                        width="300px" @change="handleShopChange" />
                    <div class="flex_row ml10 flex1">
                        <el-date-picker style="width: 300px;" size="mini" v-model="dateArray" type="daterange"
                            range-separator="至" start-placeholder="开始日期" end-placeholder="结束日期" format="yyyy-MM-dd"
                            value-format="yyyy-MM-dd" :picker-options="pickerOptions" @change="handleDateChange">
                        </el-date-picker>
                    </div>
                </div>
            </div>
            <div class="flex_column flex1">
                <div class="table_box mt5">
                    <ayjTable :columns="columnsTa" :data="tableData" :hasMore="hasMore" :loading="loading"
                        :height="dynamicHeight" @load-more="loadMoreData">
                        <template #column-profit_re="{ row }">
                            <span class="font_green"> {{ row.profit_re || 0 }} </span>
                        </template>
                    </ayjTable>
                </div>
            </div>
        </div>
    </ayjDrawer>
</template>

<script setup>
import { ref, reactive, onMounted, computed, getCurrentInstance, defineProps, defineExpose, watch } from '@vue/composition-api'
import { useDynamicHeight } from '@/hooks/useDynamicHeight'
import Select from '@/components/commV2/Select/index.vue'

const { proxy } = getCurrentInstance();
import config from "@/js/conf/Config.js";
const maxPnum = 20

const ayjDrawerRef = ref(null)
const containerBoxRef = ref(null)
const pointsBoxRef = ref(null)
const loading = ref(false)
const hasMore = ref(true)

const query = ref({
    pfrom: 0,
    pnum: maxPnum,
    devid: '',
    day_f: '',
    day_t: '',
    shopid: '',
})
const dateArray = ref('')


// 使用动态高度 hooks
const { dynamicHeight, updateHeight } = useDynamicHeight({
    containerRef: containerBoxRef,
    subtractRef: pointsBoxRef,
    extraHeight: 20 // 额外的间距
})

const tableData = ref([])
const columnsTa = computed(() => [
    {
        title: '序号',
        prop: 'index',
        width: '50px',
        align: 'center',
        render: (row, column, index) => index + 1,
    },
    { title: '用户名字', prop: 'name', align: 'left' },
    { title: '联系方式', prop: 'cellphone', align: 'left' },
    { title: '消耗次数', prop: 'livetime', align: 'left', align: 'center' },
    { title: '内容', prop: 'txt', align: 'left', width: '32%', },
    { title: '创建时间', prop: 'atime_txt', align: 'center' },
])

const props = defineProps({
    data: {
        type: Object,
        default: () => ({})
    },
    isShowDevno: {
        type: Boolean,
        default: true
    }
})

const rowData = ref({})
watch(() => props.data, (newVal) => {
    if (newVal && newVal?.id) {
        rowData.value = newVal
        query.value.devid = newVal.id
    }
    if (newVal && newVal?.type == 'allLog') {
        query.value = { ...query.value }
    }
}, { deep: true, immediate: true })


const handleDateChange = (val) => {
    query.value.pfrom = 0
    tableData.value = []
    if (val) {
        query.value.day_f = val[0]
        query.value.day_t = val[1]
    } else {
        query.value.day_f = ''
        query.value.day_t = ''
    }
    getDevsetLog()
}

// 日期选择器配置
const pickerOptions = {
    disabledDate(time) {
        return time.getTime() > Date.now()
    }
}

const handleShopChange = (val) => {
    query.value.pfrom = 0
    tableData.value = []
    getDevsetLog()
}

const getDevsetLog = async () => {
    try {
        let param = {
            ...query.value
        };
        loading.value = true
        let res = await proxy.$api({ url: config.devset_open_log, data: param });
        if (res.status == 1) {
            let list = res?.data?.ls || []
            if (list && list.length > 0) {
                tableData.value = tableData.value.concat(list || [])
                tableData.value = tableData.value.map(vm => {
                    return {
                        ...vm,
                        ...vm.customer
                    }
                })
                // hasMore.value = (list.length || 0) >= query.value.pnum ? true : false
                // 当请求第一页数据（20条），无法满足滚动情况下，继续请求第二页数据
                if (list.length >= query.value.pnum && tableData.value.length < query.value.pnum * 2) {
                    query.value.pfrom += 20
                    getDevsetLog()
                }
                if (list.length < query.value.pnum) {
                    hasMore.value = false
                }
            } else {
                hasMore.value = false
            }
        }
        loading.value = false
    } catch (error) {
        loading.value = false
        hasMore.value = false
    }
}

//  获取云店列表
const yunShopList = ref([])
const getYunShopLsFun = async () => {
    let param = {}
    try {
        let res = await proxy.$api({ url: config.YUN_SHOP_LS, data: param })
        if (res.status == 1) {
            if (res.data && res.data.length > 0) {
                yunShopList.value = res.data.map(v => {
                    return {
                        label: v.name,
                        value: v.id
                    }
                })
            }
        }
    } catch (error) {
    }
}

const open = async () => {
    ayjDrawerRef.value.open();
    query.value.pfrom = 0
    tableData.value = []
    setTimeout(() => {
        getDevsetLog()
        getYunShopLsFun()
    }, 100)
    setTimeout(() => {
        updateHeight()
    }, 250)
}

const handleClose = () => {
    resetFc()
    ayjDrawerRef.value.close();
}

const resetFc = () => {
    query.value.devid = ''
    query.value.pfrom = 0
    query.value.day_f = ''
    query.value.day_t = ''
    query.value.shopid = ''
    tableData.value = []
}

const loadMoreData = () => {
    if (loading.value && !hasMore.value) {
        return
    }
    query.value.pfrom += 20
    getDevsetLog()
}

onMounted(() => { })

defineExpose({
    open
})
</script>

<style lang="scss" scoped>
::v-deep .el-dialog__body {
    padding: 10px 0 !important;
}

.customer_points_top {
    padding: 10px;
    border-radius: 6px;
}

.select_store ::v-deep .el-input__inner {
    background-color: #f5f5f5 !important;
    border: none !important;
    color: #333 !important;
    padding-left: 4px !important;
    text-align: left !important;
    border-radius: 0 !important;
}

.customer_points_top ::v-deep .el-divider--vertical {
    height: 1.5rem !important;
    position: relative;
    left: -10px;
}

.container_box {
    box-sizing: border-box;
    border-radius: 10px;
    height: 100%;
    display: flex;
    flex-direction: column;
}

.table_box {
    flex: 1;

    ::v-deep .body-cell {
        white-space: normal !important;
        line-height: 1.5;
        height: auto;
        min-height: 32px;
        display: flex;
        align-items: center;
    }

    ::v-deep .header-cell {
        white-space: normal !important;
        line-height: 1.5;
        height: auto;
        min-height: 40px;
        display: flex;
        align-items: center;
    }
}
</style>
